package org.middleware.controller.common;

import org.middleware.utils.CaptchaUtil;
import org.middleware.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CaptchaController {

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 获取图片验证码
     * @param key 键，用户名-类型[login或者register] 的格式，例如 admin-login
     * @return
     */
    @GetMapping("/captchas")
    public CommonHttpResponse getCaptcha(@RequestParam String key) {

        if (redisUtil.get(key) != null) {
            return CommonHttpResponse.fail(400, "验证码未过期，请等1分钟后再试");
        }

        // 生成验证码
        CaptchaUtil.CaptchaResult captchaResult = CaptchaUtil.generateCaptcha();

        String base64Image = "";
        // 将图片转换为Base64,转换失败返回异常
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(captchaResult.getImage(), "jpeg", baos);
            base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());
        } catch (IOException e) {
            System.out.println(e);
            return CommonHttpResponse.fail(500, "获取验证码异常");
        }

        // 验证码上传到redis
        redisUtil.set(key, captchaResult.getText(), 60);
        Map<String, String> data = new HashMap<>();
        data.put("url", "data:image/jpeg;base64," + base64Image);

        return CommonHttpResponse.success("获取验证码成功", data);
    }

    /**
     * 验证码验证接口
     * @param key 键，用户名-类型[login或者register],例如 admin-login
     * @param code 4位验证码，不区分大小写
     * @return
     */
    @GetMapping("/verify-captcha")
    public CommonHttpResponse verifyCaptcha(@RequestParam String key, @RequestParam String code) {

        if (key == null || key.length() == 0) {
            return CommonHttpResponse.fail(400, "用户名不能为空");
        }

        if (code == null || code.length() == 0) {
            return CommonHttpResponse.fail(400, "验证码不能为空");
        }

        Object captcha = redisUtil.get(key);

        if (captcha != null && captcha.toString().equals(code.toUpperCase())) {
            redisUtil.delete(key);
            return CommonHttpResponse.success("验证通过");
        }
        return CommonHttpResponse.fail(400, "验证码错误或已过期删除");


    }
}
